<!-- <script setup>
import HelloWorld from './components/HelloWorld.vue'
</script>

<template>
  <div>
    <a href="https://vite.dev" target="_blank">
      <img src="/vite.svg" class="logo" alt="Vite logo" />
    </a>
    <a href="https://vuejs.org/" target="_blank">
      <img src="./assets/vue.svg" class="logo vue" alt="Vue logo" />
    </a>
  </div>
  <HelloWorld msg="Vite + Vue" />
</template>

<style scoped>
.logo {
  height: 6em;
  padding: 1.5em;
  will-change: filter;
  transition: filter 300ms;
}
.logo:hover {
  filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.vue:hover {
  filter: drop-shadow(0 0 2em #42b883aa);
}
</style> -->
<!-- App.vue -->
<!-- App.vue -->
<script setup>
import { ref, computed, onMounted } from 'vue'

// 学习计划列表
const plans = ref([])

// 当前表单
const newPlan = ref({
  subject: '',
  contentLines: [''], // 多行内容数组
  location: '自习室'
})

// 编辑状态
const editingId = ref(null)
const editedPlan = ref({ subject: '', contentLines: [''], location: '自习室' })

// 科目 & 地点选项
const subjects = ['vue.js','数据库','数据结构','操作系统', '其他']
const locations = ['自习室', '教室', '教师']

// === 新增：根据科目获取历史内容建议 ===
const subjectSuggestions = computed(() => {
  if (!newPlan.value.subject) return []
  return plans.value
    .filter(p => p.subject === newPlan.value.subject)
    .map(p => p.contentLines.join('\n')) // 合并为字符串
    .filter((v, i, a) => a.indexOf(v) === i) // 去重
})
const showSuggestions = ref(false)

// 选择建议内容
const selectSuggestion = (suggestion) => {
  newPlan.value.contentLines = suggestion.split('\n')
  showSuggestions.value = false
}

// === 新增：筛选逻辑（科目 + 状态）===
const filterSubject = ref('') // '' 表示全部
const filterStatus = ref('all') // 'all', 'completed', 'pending'

const filteredPlans = computed(() => {
  return plans.value.filter(plan => {
    const subjectMatch = !filterSubject.value || plan.subject === filterSubject.value
    let statusMatch = true
    if (filterStatus.value === 'completed') statusMatch = plan.completed
    else if (filterStatus.value === 'pending') statusMatch = !plan.completed
    // 'all' 时 statusMatch 为 true
    return subjectMatch && statusMatch
  })
})

// === 新增：根据当前筛选条件计算已完成/未完成数量 ===
const completedCount = computed(() => {
  return plans.value.filter(plan => {
    const subjectMatch = !filterSubject.value || plan.subject === filterSubject.value
    return subjectMatch && plan.completed
  }).length
})

const pendingCount = computed(() => {
  return plans.value.filter(plan => {
    const subjectMatch = !filterSubject.value || plan.subject === filterSubject.value
    return subjectMatch && !plan.completed
  }).length
})

// 加载数据
const loadPlans = () => {
  const saved = localStorage.getItem('studyPlans')
  if (saved) {
    plans.value = JSON.parse(saved)
  } else {
    plans.value = []
  }
}

// 保存数据
const savePlans = () => {
  localStorage.setItem('studyPlans', JSON.stringify(plans.value))
}

// 添加计划
const addPlan = () => {
  const { subject, contentLines } = newPlan.value
  const contentText = contentLines.filter(line => line.trim()).join('\n')
  if (!subject.trim() || !contentText) return

  const plan = {
    id: Date.now(),
    subject: subject.trim(),
    contentLines: contentLines.filter(line => line.trim() !== ''),
    location: newPlan.value.location,
    completed: false,
    createdAt: new Date().toLocaleString('zh-CN')
  }

  plans.value.unshift(plan)
  // 重置表单
  newPlan.value = { subject: '', contentLines: [''], location: '自习室' }
  showSuggestions.value = false
  savePlans()
}

// 删除计划
const deletePlan = (id) => {
  plans.value = plans.value.filter(p => p.id !== id)
  savePlans()
}

// 开始编辑
const startEdit = (plan) => {
  editingId.value = plan.id
  editedPlan.value = {
    subject: plan.subject,
    contentLines: [...plan.contentLines],
    location: plan.location
  }
}

// 完成编辑
const finishEdit = () => {
  const { subject, contentLines } = editedPlan.value
  const contentText = contentLines.filter(line => line.trim()).join('\n')
  if (!subject.trim() || !contentText) return

  const plan = plans.value.find(p => p.id === editingId.value)
  if (plan) {
    plan.subject = subject.trim()
    plan.contentLines = contentLines.filter(line => line.trim() !== '')
    plan.location = editedPlan.value.location
  }

  editingId.value = null
  savePlans()
}

// 取消编辑
const cancelEdit = () => {
  editingId.value = null
}

// 切换完成状态
const toggleComplete = (plan) => {
  plan.completed = !plan.completed
  savePlans()
}

// 动态添加新行
const addContentLine = (lines) => {
  lines.push('')
}

// 删除某一行
const removeContentLine = (lines, index) => {
  if (lines.length > 1) {
    lines.splice(index, 1)
  } else {
    lines[0] = '' // 至少保留一行
  }
}

// 统计（全部计划）
const totalAllPlans = () => plans.value.length

// 页面加载
onMounted(() => {
  loadPlans()
})
</script>

<template>
  <div class="container">
    <header class="header">
      <h1>📚 我的学习计划表</h1>
      <p>共 {{ totalAllPlans() }} 项计划 | 已完成 {{ plans.filter(p => p.completed).length }}</p>
    </header>

    <!-- 添加新计划 -->
    <div class="add-form">
      <select v-model="newPlan.subject" class="select" @focus="showSuggestions = true">
        <option value="" disabled>选择科目</option>
        <option v-for="sub in subjects" :key="sub" :value="sub">{{ sub }}</option>
      </select>

      <!-- 内容输入区 -->
      <div class="content-input">
        <div v-for="(line, index) in newPlan.contentLines" :key="index" class="line-item">
          <input
            v-model="newPlan.contentLines[index]"
            :placeholder="`内容第${index + 1}行`"
            @keydown.enter.prevent="addContentLine(newPlan.contentLines)"
            class="input-line"
          />
          <button
            v-if="newPlan.contentLines.length > 1"
            @click="removeContentLine(newPlan.contentLines, index)"
            class="btn remove-line"
          >
            ×
          </button>
        </div>

        <!-- 建议下拉框 -->
        <ul v-if="showSuggestions && subjectSuggestions.length > 0" class="suggestions">
          <li v-for="(sug, i) in subjectSuggestions" :key="i" @click="selectSuggestion(sug)">
            {{ sug.length > 50 ? sug.slice(0, 50) + '...' : sug }}
          </li>
        </ul>
      </div>

      <select v-model="newPlan.location" class="select">
        <option v-for="loc in locations" :key="loc" :value="loc">{{ loc }}</option>
      </select>

      <button @click="addPlan" class="btn add-btn">➕ 添加</button>
    </div>

    <!-- 表格头部：添加筛选按钮 -->
    <div class="table-header">
      <span class="col index">#</span>
      <div class="col subject">
        <select v-model="filterSubject" @change="filterStatus = 'all'">
          <option value="">全部科目</option>
          <option v-for="sub in subjects" :key="sub" :value="sub">{{ sub }}</option>
        </select>
      </div>
      <span class="col content">学习内容</span>
      <span class="col location">地点</span>
      <span class="col status">状态</span>
      <span class="col actions">操作</span>
    </div>

    <!-- 筛选按钮 -->
    <div class="filter-buttons">
      <button
        @click="filterStatus = 'all'"
        :class="['filter-btn', { active: filterStatus === 'all' }]"
      >
        全部
      </button>
      <button
        @click="filterStatus = 'completed'"
        :class="['filter-btn', { active: filterStatus === 'completed' }]"
      >
        已完成 ({{ completedCount }})
      </button>
      <button
        @click="filterStatus = 'pending'"
        :class="['filter-btn', { active: filterStatus === 'pending' }]"
      >
        未完成 ({{ pendingCount }})
      </button>
    </div>

    <!-- 计划列表 -->
    <ul class="plan-list">
      <li
        v-for="(plan, index) in filteredPlans"
        :key="plan.id"
        :class="['plan-item', { completed: plan.completed }]"
      >
        <!-- 显示模式 -->
        <template v-if="editingId !== plan.id">
          <div class="col index">{{ index + 1 }}</div>
          <div class="col subject" @click="toggleComplete(plan)">
            {{ plan.subject }}
          </div>

          <!-- ✅ 修改点：已完成时无法双击编辑 -->
          <div class="col content" @click="toggleComplete(plan)" @dblclick="!plan.completed && startEdit(plan)">
            <ul class="content-list">
              <li v-for="(line, i) in plan.contentLines" :key="i">{{ line }}</li>
            </ul>
          </div>

          <div class="col location">📍 {{ plan.location }}</div>

          <div class="col status">
            <span
              @click.stop="toggleComplete(plan)"
              :class="['status-badge', plan.completed ? 'done' : 'pending']"
            >
              {{ plan.completed ? '已完成' : '未完成' }}
            </span>
          </div>

          <div class="col actions">
            <button @click="startEdit(plan)" class="btn edit-btn">✏️</button>
            <button @click="deletePlan(plan.id)" class="btn delete-btn">🗑️</button>
          </div>
        </template>

        <!-- 编辑模式 -->
        <template v-else>
          <div class="col index">{{ index + 1 }}</div>
          <select v-model="editedPlan.subject" class="edit-select">
            <option v-for="sub in subjects" :key="sub" :value="sub">{{ sub }}</option>
          </select>

          <div class="content-input">
            <div v-for="(line, idx) in editedPlan.contentLines" :key="idx" class="line-item">
              <input
                v-model="editedPlan.contentLines[idx]"
                :placeholder="`内容第${idx + 1}行`"
                @keydown.enter.prevent="addContentLine(editedPlan.contentLines)"
                class="input-line"
              />
              <button
                v-if="editedPlan.contentLines.length > 1"
                @click="removeContentLine(editedPlan.contentLines, idx)"
                class="btn remove-line"
              >
                ×
              </button>
            </div>
          </div>

          <select v-model="editedPlan.location" class="edit-select">
            <option v-for="loc in locations" :key="loc" :value="loc">{{ loc }}</option>
          </select>

          <div class="col actions">
            <button @click="finishEdit" class="btn save-btn">✅</button>
            <button @click="cancelEdit" class="btn cancel-btn">❌</button>
          </div>
        </template>
      </li>
    </ul>

    <!-- 空状态 -->
    <div v-if="filteredPlans.length === 0" class="empty">
      🎯 没有找到符合条件的计划，快添加一个吧！
    </div>
  </div>
</template>

<style scoped>
.container {
  max-width: 1000px;
  margin: 40px auto;
  padding: 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  background: #f8f9fa;
  min-height: 100vh;
  color: #333;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.header h1 {
  font-size: 2.2em;
  margin: 0;
  color: #2c3e50;
}

.header p {
  color: #666;
  margin-top: 8px;
}

/* 表单布局 */
.add-form {
  display: grid;
  grid-template-columns: 150px 2fr 120px auto;
  gap: 10px;
  margin-bottom: 20px;
  align-items: start;
}

.select {
  padding: 12px;
  border: 2px solid #ddd;
  border-radius: 8px;
  font-size: 15px;
  background: white;
  outline: none;
}

.select:focus {
  border-color: #4a6fa5;
}

/* 内容输入区 */
.content-input {
  position: relative;
}

.line-item {
  display: flex;
  gap: 6px;
  margin-bottom: 4px;
}

.input-line {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  outline: none;
}

.input-line:focus {
  border-color: #4a6fa5;
}

.remove-line {
  background: #e74c3c;
  color: white;
  width: 30px;
  font-size: 16px;
  border-radius: 6px;
}

/* 建议下拉 */
.suggestions {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: white;
  border: 1px solid #ddd;
  border-radius: 8px;
  max-height: 200px;
  overflow-y: auto;
  z-index: 10;
  margin: 4px 0;
  padding: 8px 0;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.suggestions li {
  padding: 8px 12px;
  cursor: pointer;
  color: #333;
}

.suggestions li:hover {
  background: #f0f0f0;
}

/* 按钮 */
.btn {
  padding: 10px 14px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
}

.add-btn {
  background: #4a6fa5;
  color: white;
  align-self: start;
}

.add-btn:hover {
  background: #3a5a80;
}

.delete-btn {
  background: #e74c3c;
  color: white;
  width: 40px;
}

.delete-btn:hover {
  background: #c0392b;
}

.edit-btn {
  background: #3498db;
  color: white;
  width: 40px;
}

.edit-btn:hover {
  background: #2980b9;
}

.save-btn {
  background: #27ae60;
  color: white;
  width: 40px;
}

.save-btn:hover {
  background: #219653;
}

.cancel-btn {
  background: #95a5a6;
  color: white;
  width: 40px;
}

.cancel-btn:hover {
  background: #7f8c8d;
}

/* 表格头部 */
.table-header {
  display: grid;
  grid-template-columns: 40px 150px 2fr 120px 100px 100px; /* 新增 40px 为序号 */
  padding: 12px;
  background: #ecf0f1;
  border-radius: 8px;
  font-weight: bold;
  color: #2c3e50;
  font-size: 15px;
  margin-bottom: 10px;
  gap: 10px;
}

/* 筛选按钮 */
.filter-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.filter-btn {
  padding: 8px 16px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 20px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.filter-btn:hover {
  background: #f0f0f0;
}

.filter-btn.active {
  background: #4a6fa5;
  color: white;
  border-color: #4a6fa5;
}

/* 序号列 */
.col.index {
  text-align: center;
  font-weight: bold;
  color: #555;
  width: 40px;
  flex: none;
}

/* 计划列表 */
.plan-list {
  list-style: none;
  padding: 0;
}

.plan-item {
  display: grid;
  grid-template-columns: 40px 150px 2fr 120px 100px 100px; /* 与表头对齐 */
  gap: 10px;
  background: white;
  padding: 14px;
  margin-bottom: 10px;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.2s;
  align-items: start;
}

.plan-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.plan-item.completed .content,
.plan-item.completed .subject {
  color: #95a5a6;
}

.content-list {
  margin: 0;
  padding-left: 18px;
  font-size: 14px;
  color: #555;
}

.content-list li {
  margin: 4px 0;
}

.status-badge {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  color: white;
  cursor: pointer;
  transition: background 0.2s;
}

.status-badge.pending {
  background: #e67e22;
}

.status-badge.pending:hover {
  background: #d35400;
}

.status-badge.done {
  background: #27ae60;
}

.status-badge.done:hover {
  background: #219653;
}

.empty {
  text-align: center;
  color: #999;
  font-size: 18px;
  padding: 40px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}
</style>
